package com.kchouse.mine;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppInstallAdapter;
import com.fm.openinstall.model.AppData;
import com.kchouse.common.BaseActivity;
import com.kchouse.R;
import com.kchouse.common.API;
import com.kchouse.common.SharedPreferencesUtil;
import com.kchouse.view.ClearEditText;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import cn.jpush.android.api.JPushInterface;


/**
 * 手机验证码登录
 */
public class LoginPhoneActivity extends BaseActivity implements View.OnClickListener {


    private LoginPhoneActivity mContent;
    private ImageView iv_back;
    private View ll_login;
    private Intent intent;
    private Button bt_login;
    private TextView tv_code;
    private ClearEditText et_phone;
    private ClearEditText et_code;
//    private String refereesid="00081aa062b043dc949559a077b7d62e";//推荐人id
    private String refereesid="";//推荐人id
    private ClearEditText et_password;
    private View rl_code;
    private TextView tv_loginway;
    private boolean isway = true;//true 注册  false 登录
    private TextView tv_title;
    private String registrationID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loginphone);

        mContent = this;
        intiData();
        intiView();


        //获取OpenInstall安装数据
        OpenInstall.getInstall(new AppInstallAdapter() {
            @Override
            public void onInstall(AppData appData) {
                //获取渠道数据
//                String channelCode = appData.getChannel();
                //获取自定义数据
                String bindData = appData.getData();

                if (!TextUtils.isEmpty(bindData)) {
                    JSONObject json = JSONObject.parseObject(bindData);
                    refereesid = json.getString("value");
//                  Log.d("OpenInstall", "getInstall : installData = " + appData.toString());
                    Log.e("bindData", appData.toString());
//                    ToastUtils.getInstanc(mContent).showToast("refereesid="+refereesid);
                }


            }
        });
    }

    private void intiData() {
        intent = getIntent();

        registrationID   =  JPushInterface.getRegistrationID(mContent);
    }
    private void intiView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        ll_login = findViewById(R.id.ll_login);
        ll_login.setOnClickListener(this);
        tv_code = (TextView) findViewById(R.id.tv_code);
        tv_code.setOnClickListener(this);
        bt_login = (Button) findViewById(R.id.bt_login);
        bt_login.setOnClickListener(this);
        et_phone = (ClearEditText) findViewById(R.id.et_phone);
        et_code = (ClearEditText) findViewById(R.id.et_code);
        et_password = (ClearEditText) findViewById(R.id.et_password);
        rl_code = findViewById(R.id.rl_code);
        tv_loginway = (TextView) findViewById(R.id.tv_loginway);
        tv_title = (TextView) findViewById(R.id.tv_title);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_login:
//                intent.setClass(mContent, LoginActivity.class);
//                startActivity(intent);
//                finish();
                if (isway) {
                    rl_code.setVisibility(View.GONE);
                    et_password.setVisibility(View.VISIBLE);
                    tv_loginway.setText("验证码登录");
                    isway = false;
                    bt_login.setText("登    录");
                    tv_title.setText("密码登录");
                } else {
                    rl_code.setVisibility(View.VISIBLE);
                    et_password.setVisibility(View.GONE);
                    tv_loginway.setText("账号密码登录");
                    isway = true;
                    bt_login.setText("注    册 | 登    录");
                    tv_title.setText("验证码登录");
                }
                break;
            case R.id.tv_code://获取验证码
                if (TextUtils.isEmpty(et_phone.getText().toString())) {
                    ToastUtils.getInstanc(mContent).showToast("您还未填写电话号码");
                    return;
                }
                getcode(et_phone.getText().toString());
                break;
            case R.id.bt_login:
                if (TextUtils.isEmpty(et_phone.getText().toString())) {
                    ToastUtils.getInstanc(mContent).showToast("您还未填写电话号码");
                    return;
                }
                if (isway) {//true 注册 false 登录
                    if (TextUtils.isEmpty(et_code.getText().toString())) {
                        ToastUtils.getInstanc(mContent).showToast("您还未填写验证码");
                        return;
                    }
                    login(et_phone.getText().toString(), et_code.getText().toString());
                } else {
                    if (TextUtils.isEmpty(et_password.getText().toString())) {
                        ToastUtils.getInstanc(mContent).showToast("您还未填写密码");
                        return;
                    }
                    login2(et_phone.getText().toString(), et_password.getText().toString());
                }

                break;
        }
    }


    /**
     * 密码登录
     */
    private void login2(String mobile, String password) {
        String url = API.LoginPassWord;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        JSONObject ob = new JSONObject();
        ob.put("mobile", mobile);
        ob.put("password", password);
        ob.put("jgRegistrationId", registrationID);
//        params.addFormDataPart("file", file);//上传单个文件
//        params.addFormDataPart("files", files);//上传多个文件
//        params.addHeader("token", token);//添加header信息
        params.applicationJson(ob);

        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    ToastUtils.getInstanc(mContent).showToast("登录成功");
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    String token = data.getString("token");
                    SharedPreferencesUtil.setParam(mContent, "token", token);//保存用户token
                    String userstr = data.getString("user");
                    JSONObject user = JSONObject.parseObject(userstr);
                    String mobile = user.getString("mobile");
                    SharedPreferencesUtil.setParam(mContent, "mobile", mobile);//保存用户电话
                    String userName = user.getString("userName");
                    SharedPreferencesUtil.setParam(mContent, "userName", userName);//保存用户名
                    String id = user.getString("id");
                    SharedPreferencesUtil.setParam(mContent, "userid", id);//保存用户id
                    String qrUrl = user.getString("qrUrl");
                    SharedPreferencesUtil.setParam(mContent, "qrUrl", qrUrl);//保存用户分享链接
                    //TODO 登录时未返回积分字段

                    Intent mIntent = new Intent("LoginAction");
                    //发送广播
                    sendBroadcast(mIntent);
                    finish();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 请求验证码接口（成功开启倒计时）
     */
    private void getcode(String mobile) {
        String url = API.GetYzmCode + mobile;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("mobile", mobile);//表单数据
        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
//                toast(loginResponse.getMsg());
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    ToastUtils.getInstanc(mContent).showToast("发送成功");
                    countdown();
                } else {
                    ToastUtils.getInstanc(mContent).showToast(json.getString("发送失败"));
                }
//
            }

            /**
             * 倒计时60秒
             */
            private void countdown() {
                new CountDownTimer(60000, 1000) {

                    public void onTick(long millisUntilFinished) {
                        tv_code.setClickable(false);
                        tv_code.setText(millisUntilFinished / 1000 + "s");
                    }

                    public void onFinish() {
                        tv_code.setClickable(true);
                        tv_code.setText("获取验证码");
                    }
                }.start();
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
                ToastUtils.getInstanc(mContent).showToast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 验证码登录
     */
    private void login(String mobile, String code) {
        String url = API.LoginMoblie;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        JSONObject ob = new JSONObject();
        ob.put("mobile", mobile);
        ob.put("captcha", code);
        ob.put("userId", refereesid);
        ob.put("jgRegistrationId", registrationID);
        params.applicationJson(ob);

        Log.e("bindData", params.toString());
        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    ToastUtils.getInstanc(mContent).showToast("登录成功");
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    String token = data.getString("token");
                    SharedPreferencesUtil.setParam(mContent, "token", token);//保存用户token
                    String userstr = data.getString("user");
                    JSONObject user = JSONObject.parseObject(userstr);
                    String mobile = user.getString("mobile");
                    SharedPreferencesUtil.setParam(mContent, "mobile", mobile);//保存用户电话
                    String userName = user.getString("userName");
                    SharedPreferencesUtil.setParam(mContent, "userName", userName);//保存用户名
                    String id = user.getString("id");
                    SharedPreferencesUtil.setParam(mContent, "userid", id);//保存用户id
                    String qrUrl = user.getString("qrUrl");
                    SharedPreferencesUtil.setParam(mContent, "qrUrl", qrUrl);//保存用户分享链接
                    Intent mIntent = new Intent("LoginAction");
                    //发送广播
                    sendBroadcast(mIntent);
                    finish();
                } else {

                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

}

